<?php

declare(strict_types=1);

namespace app\controller\admin;

use app\model\admin\ApplyMoneySet;
use app\model\admin\BalanceLog;
use app\model\admin\CateModel;
use app\model\admin\MiniApply;
use app\model\admin\MiniBalanceLog;
use app\model\admin\MiniUser;
use app\model\admin\Pact;
use app\model\admin\SysMember;
use app\model\admin\SysUser;
use app\service\MemberService;
use app\service\SysUserService;
use think\facade\Db;
use think\facade\Validate;
use think\Request;

class MiniApplyController extends AdminBaseController
{
    public function getList(Request $request)
    {
        $params = $request->param();
        $official_user = $request->authInfo;
        $user_id = $official_user['user_id'];
        $mp_user_ids = [];
        if (isset($params['nickname'])) {
            $mp_user_ids = MiniUser::scope('where', ['nickname' => $params['nickname'] ?? ''])->column('id');
        }
        // 获取统计
        $success_money = MiniApply::scope('where', $params)
            // ->where('sys_user_id', $user_id)
            ->where(function ($q) use ($params, $mp_user_ids) {
                if (isset($params['nickname'])) {
                    $q->whereIn('user_id', $mp_user_ids);
                }
            })->where('status', 3)->sum('money');
        $total_money = MiniApply::scope('where', $params)
            // ->where('sys_user_id', $user_id)
            ->where(function ($q) use ($params, $mp_user_ids) {
                if (isset($params['nickname'])) {
                    $q->whereIn('user_id', $mp_user_ids);
                }
            })->sum('money');
        $fail_money = MiniApply::scope('where', $params)
            // ->where('sys_user_id', $user_id)
            ->where(function ($q) use ($params, $mp_user_ids) {
                if (isset($params['nickname'])) {
                    $q->whereIn('user_id', $mp_user_ids);
                }
            })->where('status', 4)->sum('money');
        $ing_money = number_format($total_money - $fail_money - $success_money, 2);
        $list = MiniApply::with(['user' => function ($q) {
            $q->field('nickname,id');
        }])->scope('where', $params)
            // ->where('sys_user_id', $user_id)
            ->where(function ($q) use ($params, $mp_user_ids) {
                if (isset($params['nickname'])) {
                    $q->whereIn('user_id', $mp_user_ids);
                }
            })
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $this->limit,
                'page' => $this->page,
                'var_page' => $this->pageVar
            ]);

        // return successPage($list);
        return success([
            'items' => $list->items(),
            'pageSize' => $list->listRows(),
            'pageNum' => $list->currentPage(),
            'total' => $list->total(),
            'totalPage' => $list->lastPage(),
            "sum_money" => $total_money,
            "sum_real_money" => $success_money,
            "fail_money" => $fail_money,
            "ing_money" => $ing_money,
        ]);
    }
    // 批量处理
    public function changeMore(Request $request)
    {
        $id = input('id');
        $status = input('status');
        $remark = input('remark');
        $password = input('password');
        $fail_text = input('fail_text');

        if (!is_array($id)) {
            return error('参数错误');
        }
        if (count($id) > 50) {
            return error('最多处理50条记录');
        }
        if (!$status || !$password) {
            return error('参数错误');
        }

        $auth_info = $request->authInfo;

        $user_id = $auth_info['user_id'];
        $user_type = $auth_info['user_type'];

        if ($user_type == 'admin') {
            $user = SysUser::where('id', $user_id)->find();
        } elseif ($user_type == 'user') {
            $user = SysMember::where('id', $user_id)->find();
        } else {
            // return error('未知用户类型');
        }

        // $member_user = $request->authInfo;
        // $user_id = $member_user['user_id'];
        // $users = SysMember::find($user_id);

        //验证密码
        $apply_pwd = $user->password;
        if (md5($password) != $apply_pwd) {
            return error('密码不匹配');
        }
        $list = MiniApply::with(['user'])->whereIn('id', $id)->where('status', 1)->select()->toArray();

        // if (!$info) {
        //     return error('提现记录不存在');
        // }
        foreach ($list as $key => $value) {
            if ($status == 3) {
                try {
                    $pay_info = $this->getPayInstanceByAppid($user_id);
                } catch (\Exception $e) {
                    return error("打款失败，原因：" . $e->getMessage());
                }
                if (!$pay_info['enabled']) {
                    return error($pay_info['msg']);
                }
                $payInstance = $pay_info['instance'];
                $res = $payInstance->transfer->toBalance([
                    'partner_trade_no' => $value['order_sn'], // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
                    'openid' => $value['user']['openid'],
                    'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
                    // 're_user_name' => '', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
                    'amount' => $value['money'] * 100, // 企业付款金额，单位为分
                    // 'amount' => 0.1 * 100, // 企业付款金额，单位为分
                    'desc' => $remark ?? '公众号提现打款', // 企业付款操作说明信息。必填
                ]);
                if ($res['result_code'] == "SUCCESS") {
                    $created_at = $value['created_at'];
                    MiniApply::where('id', $value['id'])->update([
                        // 打款成功
                        "status" => 3,
                        "remark" => $remark ?? '打款成功',
                        "channel_order_sn" => $res['payment_no'] ?? ''
                    ]);
                    // // 发送提现成功模版
                    // $data = [
                    //     "mp_user_id" => $value['mp_user_id'],
                    //     "sys_user_id" => $value['sys_user_id'],
                    //     "tx_money" => $value['money'],
                    //     "order_id" => null,
                    //     'type' => "tx_success",
                    //     'tx_created_at' => $created_at,
                    //     'tx_fail_text' => "",
                    //     "tx_wx_num" => $value['wx_num']
                    // ];

                    // $q_res = Queue::push(SendTemp::class, $data);
                    // if ($q_res) {
                    // } else {
                    //     storage_log('提现模版请求队列失败');
                    // }
                }
            }
            if ($status == 4) {
                // 打款失败，直接失败
                try {
                    Db::transaction(function () use ($value, $remark, $fail_text) {
                        $created_at = $value['created_at'];
                        // $value->status = 4;
                        // $value->remark = $remark ?? '打款失败';
                        // $value->fail_text = $fail_text;
                        // $value->save();
                        MiniApply::where('id', $value['id'])->update([
                            // 打款失败
                            "status" => 4,
                            "fail_text" => $fail_text,
                            "remark" => $remark ?? '打款失败'
                        ]);
                        // 给用户回退金额
                        $res = Db::table('mp_users')->where('id', $value['user_id'])->inc('balance', floatval($value['money']))->update();
                        // 记录余额
                        BalanceLog::create([
                            "user_id" => $value['user_id'],
                            "type" => 1,
                            "order_sn" => '',
                            "money" => $value['money'],
                            "bf_money" => $value['user']['balance'],
                            "af_money" => round($value['user']['balance'] + $value['money'], 2),
                            "sys_user_id" => $value['user']['create_by'],
                            "create_by" => $value['user']['create_by'],
                            "remark" => "提现失败退款",
                        ]);
                        // 发送提现失败模版
                        // $q_data = [
                        //     "mp_user_id" => $value['mp_user_id'],
                        //     "sys_user_id" => $value['sys_user_id'],
                        //     "tx_money" => $value['money'],
                        //     "order_id" => null,
                        //     'type' => "tx_fail",
                        //     'tx_created_at' => $created_at,
                        //     "tx_fail_text" => $fail_text,
                        //     "tx_wx_num" => $value['wx_num']
                        // ];
                        // // storage_log('提现' . $created_at);
                        // // storage_log('$info->created_at' . $info->created_at);
                        // $q_res = Queue::push(SendTemp::class, $q_data);
                        // if ($q_res) {
                        // } else {
                        //     storage_log('提现模版请求队列失败');
                        // }
                    });
                } catch (\Exception $e) {
                    return error($e->getMessage());
                }
            }
            if ($status == -1) {
                // 
                // $res = Db::table('apply_money')->where('id', $id)->update([
                //     "status" => 3,
                //     "channel_order_sn" => "",
                //     "updated_at" => time(),
                //     "remark" => $remark,
                //     "img" => $img
                // ]);
                // 手动打款成功
                $created_at = $value['created_at'];
                MiniApply::where('id', $value['id'])->update([
                    // 打款成功
                    "status" => 3,
                    "remark" => $remark ?? '[手动]打款成功',
                    "channel_order_sn" => ''
                ]);

                // 发送提现成功模版
                // $data = [
                //     "mp_user_id" => $value['mp_user_id'],
                //     "sys_user_id" => $value['sys_user_id'],
                //     "tx_money" => $value['money'],
                //     "order_id" => null,
                //     'type' => "tx_success",
                //     'tx_created_at' => $created_at,
                //     'tx_fail_text' => "",
                //     "tx_wx_num" => $value['wx_num']
                // ];

                // $q_res = Queue::push(SendTemp::class, $data);
                // if (!$q_res) {
                //     storage_log('提现模版请求队列失败');
                // }
            }
        }
        return success();
    }
    public function changeStatus(Request $request)
    {
        $id = input('id');
        $status = input('status');
        $remark = input('remark');
        $password = input('password');
        $fail_text = input('fail_text');
        $img = input('img');
        $official_user = $request->authInfo;
        $user_id = $official_user['user_id'];

        $user_type = $official_user['user_type'];
        // $users = MpUsers::find($user_id);
        // $users = SysMember::find($user_id);
        if ($user_type == 'admin') {
            $user = SysUser::where('id', $user_id)->find();
        } elseif ($user_type == 'user') {
            $user = SysMember::where('id', $user_id)->find();
        } else {
            // return error('未知用户类型');
        }
        // $user = auth()->user();
        // 1待打款2打款中3打款成功4打款失败
        if (!$id || !$status || !$password) {
            return error('参数错误');
        }
        //验证密码
        $apply_pwd = $user->password;
        if (md5($password) != $apply_pwd) {
            return error('密码不匹配');
        }
        $info = MiniApply::with(['user'])->find($id);
        if (!$info) {
            return error('提现记录不存在');
        }
        if ($info->status != 1) {
            return error('已打款或打款中');
        }
        $info->img = $img;

        if ($status == 3) {
            try {
                $pay_info = $this->getPayInstanceByAppid($user_id);
            } catch (\Exception $e) {
                return error("打款失败，原因：" . $e->getMessage());
            }
            if (!$pay_info['enabled']) {
                return error($pay_info['msg'], [], 501);
            }
            $payInstance = $pay_info['instance'];
            $res = $payInstance->transfer->toBalance([
                'partner_trade_no' => $info->order_sn, // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
                'openid' => $info->user->openid,
                'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
                // 're_user_name' => '', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
                'amount' => $info->money * 100, // 企业付款金额，单位为分
                // 'amount' => 0.1 * 100, // 企业付款金额，单位为分
                'desc' => $remark ?? '公众号提现打款', // 企业付款操作说明信息。必填
            ]);
            // var_dump($res);
            if ($res['result_code'] == "SUCCESS") {
                $created_at = $info->created_at;
                // 打款成功
                $info->status = 3;
                $info->channel_order_sn = $res['payment_no'] ?? '';
                $info->remark = $remark ?? '打款成功';
                // $info->fail_text = $fail_text;

                $info->save();
                // 发送提现成功模版
                // $data = [
                //     "mp_user_id" => $info->mp_user_id,
                //     "sys_user_id" => $info->sys_user_id,
                //     "tx_money" => $info->money,
                //     "order_id" => null,
                //     'type' => "tx_success",
                //     'tx_created_at' => $created_at,
                //     'tx_fail_text' => "",
                //     "tx_wx_num" => $info->wx_num
                // ];

                // $q_res = Queue::push(SendTemp::class, $data);
                // if (!$q_res) {
                //     storage_log('提现模版请求队列失败');
                // }
            } else {
                return error("打款失败：原因：" . $res['err_code_des']);
            }
            // $created_at = $info->created_at;
            // // 打款成功
            // $info->status = 3;
            // $info->remark = $remark ?? '打款成功';
            // // $info->fail_text = $fail_text;

            // $info->save();
            // // 发送提现成功模版
            // $data = [
            //     "mp_user_id" => $info->mp_user_id,
            //     "sys_user_id" => $info->sys_user_id,
            //     "tx_money" => $info->money,
            //     "order_id" => null,
            //     'type' => "tx_success",
            //     'tx_created_at' => $created_at,
            //     'tx_fail_text' => "",
            //     "tx_wx_num" => $info->wx_num
            // ];

            // $q_res = Queue::push(SendTemp::class, $data);
            // if ($q_res) {
            // } else {
            //     storage_log('提现模版请求队列失败');
            // }

            // 1todo提交到支付宝，需要将状态修改为打款中
            // 
            // try {
            //     ApplyMoneyService::alipayTransfer($info->order_sn, $info->zfb_account, $info->user->real_name, $info->real_money, $remark);
            // } catch (\Exception $e) {
            //     return error($e->getMessage());
            // }
        }
        if ($status == 4) {
            // 打款失败，直接失败
            try {
                Db::transaction(function () use ($info, $remark, $fail_text) {
                    $created_at = $info->created_at;
                    $info->status = 4;
                    $info->remark = $remark ?? '打款失败';
                    $info->fail_text = $fail_text;
                    $info->save();
                    // 给用户回退金额
                    $res = Db::table('mini_user')->where('id', $info->user_id)->inc('balance', floatval($info->money))->update();
                    // 记录余额 
                    BalanceLog::create([
                        "user_id" => $info->user_id,
                        "type" => 1,
                        "order_sn" => '',
                        "money" => $info->money,
                        "bf_money" => $info->user->balance,
                        "af_money" => round($info->user->balance + $info->money, 2),
                        // "sys_user_id" => $info->user->create_by,
                        "create_by" => $info->user->create_by,
                        "remark" => "提现失败退款",
                    ]);
                    // 发送提现失败模版
                    // $q_data = [
                    //     "mp_user_id" => $info->mp_user_id,
                    //     "sys_user_id" => $info->sys_user_id,
                    //     "tx_money" => $info->money,
                    //     "order_id" => null,
                    //     'type' => "tx_fail",
                    //     'tx_created_at' => $created_at,
                    //     "tx_fail_text" => $fail_text,
                    //     "tx_wx_num" => $info->wx_num
                    // ];
                    // // storage_log('提现' . $created_at);
                    // // storage_log('$info->created_at' . $info->created_at);
                    // $q_res = Queue::push(SendTemp::class, $q_data);
                    // if ($q_res) {
                    // } else {
                    //     storage_log('提现模版请求队列失败');
                    // }
                });
            } catch (\Exception $e) {
                return error($e->getMessage());
            }
        }
        if ($status == -1) {
            // 
            // $res = Db::table('apply_money')->where('id', $id)->update([
            //     "status" => 3,
            //     "channel_order_sn" => "",
            //     "updated_at" => time(),
            //     "remark" => $remark,
            //     "img" => $img
            // ]);
            // 手动打款成功
            $created_at = $info->created_at;
            $info->status = 3;
            $info->channel_order_sn =  '';
            $info->remark = $remark ?? '[手动]打款成功';
            $info->save();
            // 发送提现成功模版
            // $data = [
            //     "mp_user_id" => $info->mp_user_id,
            //     "sys_user_id" => $info->sys_user_id,
            //     "tx_money" => $info->money,
            //     "order_id" => null,
            //     'type' => "tx_success",
            //     'tx_created_at' => $created_at,
            //     'tx_fail_text' => "",
            //     "tx_wx_num" => $info->wx_num
            // ];

            // $q_res = Queue::push(SendTemp::class, $data);
            // if (!$q_res) {
            //     storage_log('提现模版请求队列失败');
            // }
        }
        // if ($status == -1) {
        //     // 手动打款
        //     $res = Db::table('apply_money')->where('id', $id)->update([
        //         "status" => 3,
        //         "channel_order_sn" => "",
        //         "updated_at" => time(),
        //         "remark" => $remark,
        //         "img" => $img
        //     ]);
        // }
        return success();
    }
    public function getApplyDetail()
    {
        $id = input('id');
        if (!$id) {
            return error(' ID不能为空');
        }
        $info = MiniApply::find($id);
        if (!$info) {
            return error('记录不存在');
        }
        if ($info->status != 3) {
            // return error('当前状态不允许查看');
        }
        if ($info->img) {
            return success($info);
            // return success(['data' => env('APP_URL') . '/' . $info->getRawOriginal('img')]);
        } else {
            return  error('无凭证');
        }
    }
}
